package com.hyperfix.user.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hyperfix.common.exception.CustomException;
import com.hyperfix.common.holder.UserHolder;
import com.hyperfix.common.service.MailService;
import com.hyperfix.models.common.R;
import com.hyperfix.models.user.dtos.UserDTO;
import com.hyperfix.models.user.dtos.UserInfoDTO;
import com.hyperfix.models.user.pojos.User;
import com.hyperfix.models.user.pojos.UserInfo;
import com.hyperfix.models.user.vos.NewUserVO;
import com.hyperfix.models.user.vos.UserInfoQueryVO;
import com.hyperfix.models.user.vos.UserInfoVO;
import com.hyperfix.user.mapper.UserInfoMapper;
import com.hyperfix.user.mapper.UserMapper;
import com.hyperfix.user.service.UserInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

import static com.hyperfix.models.constant.common.RandomPasswordConstant.ORIGIN_PASSWORD;

/**
 * @author JiangChunYu
 * 2024/4/7
 */
@Transactional
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {
    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private MailService mailService;

    @Override
    public R<UserInfoDTO> getUserInfoByUsername(String username) {
        UserInfoDTO userInfo = userInfoMapper.selectUserInfoByUsername(username);
        if (userInfo == null) {
            return R.error("用户信息不存在");
        }
        return R.success(userInfo);
    }

    @Override
    public R<String> updateInfo(UserInfoVO userInfoVO) {
        boolean isUpdated = userInfoMapper.updateInfo(userInfoVO);
        if (!isUpdated) {
            throw new CustomException("用户信息修改失败，用户不存在");
        }
        return R.success("用户信息修改成功");
    }

    @Override
    public R<String> delete(String username) {
        // 判断是否是自己
        UserDTO userDTO = UserHolder.getUser();
        if (userDTO.getUsername().equals(username)) {
            return R.error("不能自己删除自己");
        }
        // 删除用户信息
        boolean isDeletedUserInfo = userInfoMapper.deleteUserInfoByUsername(username);
        if (!isDeletedUserInfo) {
            throw new CustomException("用户删除失败，用户信息不存在");
        }
        // 删除用户
        int deleteRows = userMapper.delete(new LambdaQueryWrapper<User>().eq(User::getUsername, username));
        if (deleteRows <= 0) {
            return R.error("用户删除失败，用户不存在");
        }
        return R.success("用户删除成功");
    }

    @Override
    public R<String> addUser(NewUserVO newUserVO) {
        // 检查账号是否存在
        boolean usernameExist = userMapper.isUsernameExist(newUserVO.getUsername());
        if (usernameExist) {
            return R.error("添加用户失败，账号已存在");
        }
        // 用户
        User user = new User();
        BeanUtils.copyProperties(newUserVO, user);
        user.setRegistrationTime(LocalDateTime.now());
        // 生成随机初始密码
        String initPassword = RandomUtil.randomString(ORIGIN_PASSWORD, 10);
        String encryptedInitPassword = DigestUtils.md5DigestAsHex(initPassword.getBytes());
        user.setPassword(encryptedInitPassword);
        int insertUserRows = userMapper.insert(user);
        if (insertUserRows == 0) {
            throw new CustomException("系统错误，添加用户失败");
        }
        // 用户信息
        Integer userId = user.getId();
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(newUserVO, userInfo);
        userInfo.setUserId(userId);
        int insertUserInfoRows = userInfoMapper.insert(userInfo);
        if (insertUserInfoRows == 0) {
            throw new CustomException("系统错误，添加用户信息失败");
        }
        // 给用户发送邮件，告知初始密码
        Map<String, Object> values = new HashMap<>();
        values.put("name", userInfo.getName());
        values.put("username", user.getUsername());
        values.put("password", initPassword);
        mailService.sendEmailToUser(userInfo.getEmail(), "newUser", values);
        return R.success("添加用户成功");
    }

    @Override
    public R<IPage<UserInfoDTO>> list(Integer pageNum, Integer size, UserInfoQueryVO userInfoQueryVO) {
        IPage<UserInfoDTO> userInfoDTOPage = new Page<>(pageNum, size);
        userInfoDTOPage = userInfoMapper.listUserInfoDTO(userInfoDTOPage, userInfoQueryVO);
        return R.success(userInfoDTOPage);
    }
}
